package com.frxuexi.mymvi

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class AppsViewModel @Inject constructor(private val appsRepository: AppsRepository):ViewModel() {
    //存放管理意图的管道
    val channel= Channel<AppsIntent>(Channel.UNLIMITED)

    //用于更新UI的状态封装
    private var _state= MutableStateFlow<AppsState>(AppsState.onLoading)
    val state:StateFlow<AppsState>
        get() = _state

    init {
        viewModelScope.launch {
            channel.receiveAsFlow().collect{
                when(it){
                    is AppsIntent.getApps->{
                        getapp()
                    }
                }
            }
        }
    }

    private fun getapp() {
        viewModelScope.launch {
            appsRepository.getApps()
                .flowOn(Dispatchers.IO)//子线程
                .catch {
                    Log.i("===",it.message.toString())
                }.collect{
                    if(it.code==0){
                        _state.value=AppsState.onSuccess(it.data)
                    }else{
                        _state.value=AppsState.onError(it.msg)
                    }
                }
        }
    }


}